# *********************************************************************
class SQLTable(object):
	
	# -------------------------------------------------------------------
	def __init__(self, app, name, fields):
		self.app		=	app
		self.name		=	name
		self.tablename	=	'%s_%s' % (app, name)
		self.fields	=	fields

# *********************************************************************
class SQLObject(object):
	
	# -------------------------------------------------------------------
	def __init__(self):
		self._data 		= []
		self._changed	=	[]
		
	# -------------------------------------------------------------------
	def __getitem__(self, k):
		if not self._tabledef.has_key(k):
			raise IndexException('%s is not a field in %s' % (k, self._tablename) )
		
		return self._data.get(k)
		
	# -------------------------------------------------------------------
	def __setitem__(self, k, v):
		if not self._tabledef.has_key(k):
			raise IndexException('%s is not a field in %s' % (k, self._tablename) )
		
		self._changed.append(k)
		self._data[k] = v
		return
		
	# -------------------------------------------------------------------
	def __delitem__(self, k):
		if k not in self._tabledef.keys():
			raise IndexException('%s is not a field in %s' % (k, self._tablename) )
		
		if self._data.has_key(k):
			del self._data[k]
			
		if self._changed.has_key(k):
			del self._data[k]
			
	# -------------------------------------------------------------------
	def Save(self):
		if not len(self._changed):
			return
		
		if self._data.has_key('id'):
			q = 'UPDATE %s SET ' % self._tablename
			
			fields = []
			
			for f in self._changed:
				fields.append('%s = %s' % (f, 
					self._db.Store( self._data[v], self._tabledef[f]['type']) )
				)
			
			q += ','.join(fields)
		else:
			q = 'INSERT INTO %s(' % self._tablename
			q += ','.join( self._changed )
			q += ') VALUES('
			
			fields = []
			
			for f in self._changed:
				fields.append( self._db.Store( self._data[v], self._tabledef[f]['type']) )
			
			q += ','.join(fields)
			q += ')'
			
		self._db.Query(q)
		self._changed = []	
		
	# -------------------------------------------------------------------
	def Load(self, cond, fields = None):
		if not fields:
			fields = self._tabledef.keys()
			
		q = 'SELECT %s FROM %s WHERE %s LIMIT 1' % (fields, self._tablename, cond)
		
